package com.example.attrimirror.ui.checkin;

import android.os.Bundle;
import android.os.Environment;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import android.app.AlertDialog;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.graphics.Typeface;
import android.view.inputmethod.InputMethodManager;
import android.content.Context;
import android.util.TypedValue;
import java.util.function.Consumer;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.attrimirror.R;
import com.example.attrimirror.databinding.FragmentCheckinBinding;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import com.example.attrimirror.utils.CollectionManager;
import com.example.attrimirror.model.CheckinRecord;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import com.example.attrimirror.model.Attribute;
import java.util.ArrayList;
import com.example.attrimirror.model.CheckinRecord.DailyItem;
import com.example.attrimirror.model.CheckinRecord.ChoreItem;
import com.example.attrimirror.model.CheckinRecord.SuggestionItem;
import android.widget.ImageButton;
import com.example.attrimirror.utils.LunarCalendar;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.widget.Button;
import java.text.ParseException;
import android.widget.CheckBox;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class CheckinFragment extends Fragment {

    private FragmentCheckinBinding binding;
    private SimpleDateFormat dateFormat;
    private SimpleDateFormat dateKey;
    private File checkinFile;
    private Gson gson;
    private Calendar selectedDate;
    private Map<String, CheckinRecord> checkinRecords = new HashMap<>();
    private static final String CHANNEL_ID = "attribute_notification";
    private static final String CHANNEL_NAME = "属性变化通知";
    private static final String CHANNEL_DESC = "显示属性等级变化的通知";
    private static final int NOTIFICATION_ID_BASE = 2000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createNotificationChannel();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            channel.setDescription(CHANNEL_DESC);

            NotificationManager notificationManager = requireContext().getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        CheckinViewModel checkinViewModel =
                new ViewModelProvider(this).get(CheckinViewModel.class);

        binding = FragmentCheckinBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINESE);
        dateKey = new SimpleDateFormat("yyyyMMdd", Locale.CHINESE);
        gson = new GsonBuilder().setPrettyPrinting().create();

        // 设置日历以周一为一周的第一天
        binding.calendarView.setFirstDayOfWeek(Calendar.MONDAY);

        // 初始化签到记录 Map
        if (checkinRecords == null) {
            checkinRecords = new HashMap<>();
        }

        // 加载数据
        initCheckinFile();
        loadCheckinData();

        // 初始化签到按钮为今天的状态
        Calendar today = Calendar.getInstance();
        selectedDate = today;
        binding.checkinButton.setText("签到");
        binding.checkinButton.setOnClickListener(v -> showCheckinDialog(selectedDate));

        // 设置设置按钮点击事件
        binding.btnSettings.setOnClickListener(v -> showCheckinSettings());

        // 修改日历监听器，显示选中日期的笔记
        binding.calendarView.setOnDateChangeListener((view, year, month, dayOfMonth) -> {
            selectedDate = Calendar.getInstance();
            selectedDate.set(year, month, dayOfMonth);
            String dateStr = dateKey.format(selectedDate.getTime());

            // 更新日期显示
            updateDateDisplay(selectedDate);
            binding.noteCard.setVisibility(View.VISIBLE);

            // 显示笔记
            CheckinRecord record = checkinRecords.get(dateStr);
            displayNote(record, dateStr);

            // 更新按钮状态
            updateCheckinButton(selectedDate);
        });

        // 初始显示今天的记录
        String todayStr = dateKey.format(today.getTime());
        updateDateDisplay(today);
        binding.noteCard.setVisibility(View.VISIBLE);
        displayNote(checkinRecords.get(todayStr), todayStr);

        return root;
    }

    private void updateCheckinButton(Calendar date) {
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);

        date = (Calendar) date.clone();
        date.set(Calendar.HOUR_OF_DAY, 0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 0);
        date.set(Calendar.MILLISECOND, 0);

        String dateStr = dateKey.format(date.getTime());
        boolean hasCheckedInToday = false;
        boolean isFirstCheckin = true;

        if (checkinRecords.containsKey(dateStr)) {
            hasCheckedInToday = true;
            isFirstCheckin = !checkinRecords.get(dateStr).isFirstCheckin();
        }

        if (isSameDay(date, today)) {
            binding.checkinButton.setEnabled(true);
            binding.checkinButton.setText(isFirstCheckin ? "签到" : "再次签到");
        } else if (date.before(today)) {
            binding.checkinButton.setEnabled(true);
            if (hasCheckedInToday) {
                binding.checkinButton.setText("补签");
            } else {
                binding.checkinButton.setText("补签 (消耗1颗补签珠)");
            }
        } else {
            binding.checkinButton.setEnabled(false);
            binding.checkinButton.setText("不能签到未来的日期");
        }
    }

    private boolean isSameDay(Calendar cal1, Calendar cal2) {
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) &&
                cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
    }

    private void showCheckinDialog(Calendar date) {
        boolean isRetroactive = !isSameDay(date, Calendar.getInstance());
        String dateStr = dateKey.format(date.getTime());
        boolean isFirstCheckin = !checkinRecords.containsKey(dateStr);

        // 只有第一次补签才需要补签珠
        if (isRetroactive && isFirstCheckin) {
            CollectionManager collectionManager = new CollectionManager(requireContext());
            if (!collectionManager.hasBall()) {
                Toast.makeText(getContext(), "首次补签需要消耗1颗补签珠！", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        EditText input = new EditText(requireContext());
        input.setHint("直接粘贴代码");
        input.setMinLines(3);
        input.setGravity(Gravity.TOP | Gravity.START);

        new AlertDialog.Builder(requireContext())
                .setTitle(isRetroactive ? "补签" : "签到")
                .setView(input)
                .setPositiveButton("保存", (dialog, which) -> {
                    String inputText = input.getText().toString().trim();
                    if (inputText.isEmpty()) {
                        Toast.makeText(getContext(), "请输入签到内容", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {
                        List<String> chores = new ArrayList<>();
                        List<String> suggestions = new ArrayList<>();
                        List<String> routines = new ArrayList<>();
                        Map<String, Double> attributeChanges = new HashMap<>();

                        boolean inChores = false;
                        boolean inSuggestions = false;
                        boolean inDaily = false;

                        String[] lines = inputText.split("\n");
                        for (String line : lines) {
                            line = line.trim();
                            if (line.isEmpty()) continue;

                            if (line.contains("\"chores\":")) {
                                inChores = true;
                                inSuggestions = false;
                                inDaily = false;
                                continue;
                            } else if (line.contains("\"suggestions\":")) {
                                inChores = false;
                                inSuggestions = true;
                                inDaily = false;
                                continue;
                            } else if (line.contains("\"daily\":")) {
                                inChores = false;
                                inSuggestions = false;
                                inDaily = true;
                                continue;
                            }

                            // 移除开头的{和结尾的}以及逗号
                            line = line.replaceAll("^\\{|\\}$|,$", "");
                            String[] parts = line.split(":", 2);
                            if (parts.length != 2) continue;

                            String key = parts[0].trim().replaceAll("\"", "");
                            String value = parts[1].trim();

                            if ((key.equals("note") && inChores) ||
                                    (key.equals("advice") && inSuggestions) ||
                                    (key.equals("routine") && inDaily)) {
                                // 只提取引号中的内容
                                int startQuote = value.indexOf('"');
                                int endQuote = value.lastIndexOf('"');
                                if (startQuote != -1 && endQuote != -1 && endQuote > startQuote) {
                                    String content = value.substring(startQuote + 1, endQuote);
                                    if (inChores) {
                                        chores.add(content);
                                    } else if (inSuggestions) {
                                        suggestions.add(content);
                                    } else if (inDaily) {
                                        routines.add(content);
                                    }
                                }
                            } else if (key.startsWith("attribute.")) {
                                try {
                                    // 保留数字、小数点和负号
                                    value = value.replaceAll("[^-0-9.]", "");
                                    // 解析为double并四舍五入到一位小数
                                    double expChange = Math.round(Double.parseDouble(value) * 10.0) / 10.0;
                                    attributeChanges.put(key, expChange);
                                } catch (NumberFormatException e) {
                                    // 忽略无效的数值
                                }
                            }
                        }

                        if (chores.isEmpty() && suggestions.isEmpty() && routines.isEmpty() &&
                                attributeChanges.isEmpty()) {
                            Toast.makeText(getContext(), "请输入至少一条内容", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        // 先更新属性经验值
                        updateAttributes(attributeChanges);

                        // 然后保存签到记录
                        saveCheckinRecord(date, chores, suggestions, routines, isRetroactive);

                    } catch (Exception e) {
                        Toast.makeText(getContext(), "输入格式错误", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void saveCheckinRecord(Calendar date, List<String> newChores,
                                   List<String> newSuggestions, List<String> newRoutines,
                                   boolean isRetroactive) {
        String dateStr = dateKey.format(date.getTime());
        boolean isFirstCheckin = !checkinRecords.containsKey(dateStr);

        List<DailyItem> daily = new ArrayList<>();
        List<ChoreItem> chores = new ArrayList<>();
        List<SuggestionItem> suggestions = new ArrayList<>();

        // 如果不是第一次签到，合并之前的记录
        if (!isFirstCheckin) {
            CheckinRecord oldRecord = checkinRecords.get(dateStr);
            if (oldRecord != null) {
                if (oldRecord.getDaily() != null) {
                    daily.addAll(oldRecord.getDaily());
                }
                if (oldRecord.getChores() != null) {
                    chores.addAll(oldRecord.getChores());
                }
                if (oldRecord.getSuggestions() != null) {
                    suggestions.addAll(oldRecord.getSuggestions());
                }
            }
        }

        // 添加新的记录
        if (newRoutines != null) {
            for (String routine : newRoutines) {
                DailyItem item = new DailyItem();
                item.setRoutine(routine);
                daily.add(item);
            }
        }
        if (newChores != null) {
            for (String note : newChores) {
                ChoreItem item = new ChoreItem();
                item.setNote(note);
                chores.add(item);
            }
        }
        if (newSuggestions != null) {
            for (String advice : newSuggestions) {
                SuggestionItem item = new SuggestionItem();
                item.setAdvice(advice);
                suggestions.add(item);
            }
        }

        CheckinRecord record = new CheckinRecord(dateStr, daily, chores, suggestions,
                isRetroactive, isFirstCheckin);

        if (isRetroactive && isFirstCheckin) {
            CollectionManager collectionManager = new CollectionManager(requireContext());
            collectionManager.consumeBall();
        }

        // 保存签到记录
        checkinRecords.put(dateStr, record);
        saveCheckinData();

        // 只有第一次签到才获得勋章
        if (isFirstCheckin) {
            handleCheckinSuccess(date, isRetroactive);
        }

        // 更新UI，显示多行笔记
        binding.noteCard.setVisibility(View.VISIBLE);
        updateDateDisplay(date);

        // 构建显示文本
        StringBuilder content = new StringBuilder();

        // 1. 显示日程
        if (!daily.isEmpty()) {
            content.append("<p><strong><big>")
                    .append(getString(R.string.title_daily))
                    .append("</big></strong></p>");

            for (int i = 0; i < daily.size(); i++) {
                content.append("<p>")
                        .append(String.format("%d. %s", i + 1, daily.get(i).getRoutine()))
                        .append("</p>");
            }
        }

        // 2. 显示总结
        if (!chores.isEmpty()) {
            if (content.length() > 0) content.append("<br>");

            content.append("<p><strong><big>")
                    .append(getString(R.string.title_summary))
                    .append("</big></strong></p>");

            for (ChoreItem chore : chores) {
                content.append("<p>")
                        .append(chore.getNote())
                        .append("</p>");
            }
        }

        // 3. 显示建议
        if (!suggestions.isEmpty()) {
            if (content.length() > 0) content.append("<br>");

            content.append("<p><strong><big>")
                    .append(getString(R.string.title_suggestions))
                    .append("</big></strong></p>");

            for (SuggestionItem suggestion : suggestions) {
                content.append("<p>")
                        .append(suggestion.getAdvice())
                        .append("</p>");
            }
        }

        // 使用 HTML 格式显示文本，启用 HTML 格式化
        binding.noteContent.setText(android.text.Html.fromHtml(content.toString()));

        updateCheckinButton(date);

        // 显示签到成功提示
        String message = isRetroactive ?
                (isFirstCheckin ? "补签成功！" : "已补签") :
                (isFirstCheckin ? "签到成功！获得今日勋章" : "已签到");
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }

    private void updateAttributes(Map<String, Double> changes) {
        if (changes.isEmpty()) return;

        File dataDir = new File(Environment.getExternalStorageDirectory(), "AttriMirror/data");
        File attributeFile = new File(dataDir, "attribute.json");

        try {
            // 读取当前属性数据
            Type type = new TypeToken<List<Attribute>>(){}.getType();
            List<Attribute> attributes;
            try (FileReader reader = new FileReader(attributeFile)) {
                attributes = gson.fromJson(reader, type);
            }

            // 更新属性经验值
            boolean hasChanges = false;
            int notificationCount = 0;

            for (Attribute attr : attributes) {
                String attrId = attr.getId();
                if (changes.containsKey(attrId)) {
                    double expChange = changes.get(attrId);
                    int oldLevel = attr.getLevel();
                    double oldExp = attr.getExperience();

                    if (expChange > 0) {
                        // 升级逻辑保持不变
                        double newExp = oldExp + expChange;
                        attr.setExperience(newExp);

                        while (attr.getExperience() >= attr.getRequiredExperience()) {
                            double overflow = attr.getExperience() - attr.getRequiredExperience();
                            attr.setLevel(attr.getLevel() + 1);
                            attr.setExperience(overflow);
                        }
                    } else if (expChange < 0) {
                        // 降级逻辑
                        double newExp = oldExp + expChange;  // 直接计算新的经验值

                        if (attr.getLevel() > 0) {
                            // 如果当前等级大于0，执行降级逻辑
                            while (newExp < 0 && attr.getLevel() > 0) {
                                attr.setLevel(attr.getLevel() - 1);  // 降一级
                                newExp += attr.getRequiredExperience();  // 加上降级后的等级所需经验
                            }
                        }
                        // 设置新的经验值（允许为负）
                        attr.setExperience(newExp);
                    }

                    // 如果等级发生变化，发送通知
                    if (attr.getLevel() != oldLevel) {
                        showAttributeLevelChangeNotification(
                                attr.getName(),
                                oldLevel,
                                attr.getLevel(),
                                notificationCount++
                        );
                    }

                    hasChanges = true;
                }
            }

            // 保存更新后的属性数据
            if (hasChanges) {
                try (FileWriter writer = new FileWriter(attributeFile)) {
                    gson.toJson(attributes, writer);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "更新属性数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void showAttributeLevelChangeNotification(String attrName, int oldLevel, int newLevel, int notificationOffset) {
        try {
            String title = newLevel > oldLevel ? "属性等级提升" : "属性等级降低";
            String content = newLevel > oldLevel ?
                    String.format("恭喜！您的【%s】等级升到了%d级", attrName, newLevel) :
                    String.format("很遗憾，您的【%s】等级降低到了%d级", attrName, newLevel);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(requireContext(), CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_notification)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(requireContext());
            // 使用不同的通知ID，确保多个属性变化的通知都能显示
            notificationManager.notify(NOTIFICATION_ID_BASE + notificationOffset, builder.build());
        } catch (SecurityException e) {
            Toast.makeText(requireContext(), "无法显示通知，请检查通知权限", Toast.LENGTH_SHORT).show();
        }
    }

    // 初始化打卡数据文件
    private void initCheckinFile() {
        if (getContext() != null) {
            // 获取外部存储的应用专属目录
            File appDir = new File(Environment.getExternalStorageDirectory(), "AttriMirror");
            File dataDir = new File(appDir, "data");
            if (!dataDir.exists()) {
                if (!dataDir.mkdirs()) {
                    Toast.makeText(getContext(), "创建数据目录失败", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            checkinFile = new File(dataDir, "checkin.json");
            try {
                if (!checkinFile.exists()) {
                    if (!checkinFile.createNewFile()) {
                        Toast.makeText(getContext(), "创建打卡数据文件失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    // 创建新文件时写入空的打卡记录
                    saveCheckinData();
                }
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "创建打卡数据文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 加载打卡数据
    private void loadCheckinData() {
        try {
            if (checkinFile != null && checkinFile.exists()) {
                try (FileReader reader = new FileReader(checkinFile)) {
                    Type type = new TypeToken<HashMap<String, CheckinRecord>>(){}.getType();
                    Map<String, CheckinRecord> loaded = gson.fromJson(reader, type);
                    if (loaded != null) {
                        checkinRecords = loaded;
                    } else {
                        // 如果加载的数据为空，使用空的 HashMap
                        checkinRecords = new HashMap<>();
                    }
                }
            } else {
                // 如果文件不存在，使用空的 HashMap
                checkinRecords = new HashMap<>();
            }
        } catch (Exception e) {
            // 捕获所有异常，包括 JsonSyntaxException
            e.printStackTrace();
            Toast.makeText(getContext(), "加载签到数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            // 出错时使用空的 HashMap
            checkinRecords = new HashMap<>();
        }
    }

    // 保存打卡数据
    private void saveCheckinData() {
        try {
            if (checkinFile != null) {
                // 确保目录存在
                checkinFile.getParentFile().mkdirs();

                try (FileWriter writer = new FileWriter(checkinFile)) {
                    if (checkinRecords == null) {
                        checkinRecords = new HashMap<>();
                    }
                    gson.toJson(checkinRecords, writer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "保存签到数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void handleCheckinSuccess(Calendar date, boolean isRetroactive) {
        // 添加对应的勋章
        CollectionManager collectionManager = new CollectionManager(requireContext());
        
        try {
            // 将日期字符串解析为Calendar对象
            SimpleDateFormat parser = new SimpleDateFormat("yyyyMMdd", Locale.CHINESE);
            Date parsedDate = parser.parse(dateKey.format(date.getTime()));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parsedDate);
            
            // 直接使用解析后的日期调用addDailyMedal
            collectionManager.addDailyMedal(calendar);
        } catch (ParseException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "解析日期失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void displayNote(CheckinRecord record, String dateStr) {
        binding.noteCard.setVisibility(View.VISIBLE);
        updateDateDisplay(selectedDate);
        
        // 清空之前的内容
        binding.noteContent.setVisibility(View.VISIBLE);
        StringBuilder content = new StringBuilder();
        
        if (record != null) {
            CheckinRecord.DisplaySettings settings = CheckinRecord.getDisplaySettings();
            
            // 1. 显示日程
            if (settings.isShowDaily() && record.getDaily() != null && !record.getDaily().isEmpty()) {
                content.append("<p><strong><big>日程</big></strong></p>");
                int index = 1;
                for (DailyItem item : record.getDaily()) {
                    content.append("<p>")
                          .append(index++)
                          .append(". ")
                          .append(item.getRoutine())
                          .append("</p>");
                }
            }
            
            // 2. 显示总结
            if (settings.isShowChores() && record.getChores() != null && !record.getChores().isEmpty()) {
                if (content.length() > 0) content.append("<br>");
                content.append("<p><strong><big>总结</big></strong></p>");
                for (ChoreItem chore : record.getChores()) {
                    content.append("<p>")
                          .append(chore.getNote())
                          .append("</p>");
                }
            }
            
            // 3. 显示建议
            if (settings.isShowSuggestions() && record.getSuggestions() != null && !record.getSuggestions().isEmpty()) {
                if (content.length() > 0) content.append("<br>");
                content.append("<p><strong><big>建议</big></strong></p>");
                for (SuggestionItem suggestion : record.getSuggestions()) {
                    content.append("<p>")
                          .append(suggestion.getAdvice())
                          .append("</p>");
                }
            }
            
            // 使用 HTML 格式显示文本
            binding.noteContent.setText(android.text.Html.fromHtml(content.toString()));
        } else {
            binding.noteContent.setText("这一天还没有签到记录");
        }
    }

    private void handleCheckin() {
        // 获取当前时间
        Calendar calendar = Calendar.getInstance();
        String dateStr = dateKey.format(calendar.getTime());

        // 检查是否是第一次签到（用于决定是否获得勋章）
        boolean isFirstTime = isFirstCheckin(dateStr);

        // 创建签到记录
        CheckinRecord record = new CheckinRecord(
                dateStr,
                new ArrayList<>(),
                new ArrayList<>(),
                new ArrayList<>(),
                false,
                false
        );

        // 保存记录
        checkinRecords.put(dateStr, record);
        saveCheckinData();

        // 如果是第一次签到，才发放勋章
        if (isFirstTime) {
            handleCheckinSuccess(calendar, false);
        }

        // 刷新显示
        displayNote(record, dateStr);

        // 显示签到成功提示
        Toast.makeText(getContext(), "签到成功！", Toast.LENGTH_SHORT).show();
    }

    private void handleRetroactiveCheckin(long timestamp) {
        // 使用指定的时间戳创建日历对象
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timestamp);
        String dateStr = dateKey.format(calendar.getTime());

        // 检查是否是第一次签到（用于决定是否获得勋章）
        boolean isFirstTime = isFirstCheckin(dateStr);

        // 创建签到记录
        CheckinRecord record = new CheckinRecord(
                dateStr,
                new ArrayList<>(),
                new ArrayList<>(),
                new ArrayList<>(),
                true,
                false
        );

        // 保存记录
        checkinRecords.put(dateStr, record);
        saveCheckinData();

        // 如果是第一次签到，才发放勋章
        if (isFirstTime) {
            handleCheckinSuccess(calendar, true);
        }

        // 刷新显示
        displayNote(record, dateStr);

        // 显示补签成功提示
        Toast.makeText(getContext(), "补签成功！", Toast.LENGTH_SHORT).show();
    }

    private int findSectionEnd(String sectionTag) {
        return 0;
    }

    private View createEditableItem(String text, Consumer<String> onEditComplete, Runnable onDelete,
                                    Runnable onMoveUp, Runnable onMoveDown, boolean isRoutine) {
        return null;
    }

    private void addEditableItem(String text, Consumer<String> onEditComplete, Runnable onDelete,
                                 Runnable onMoveUp, Runnable onMoveDown, boolean isRoutine) {
    }

    private void addSectionTitle(String title, Runnable onAdd) {
    }

    private void updateDateDisplay(Calendar date) {
        String dateStr = dateFormat.format(date.getTime());
        String weekDay = getWeekDay(date);
        String lunarDate = LunarCalendar.getLunarDate(date);

        binding.dateDisplay.setText(String.format("%s %s\n%s", dateStr, weekDay, lunarDate));
    }

    private String getWeekDay(Calendar calendar) {
        String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 将 Calendar.DAY_OF_WEEK 转换为我们需要的格式（周一=0，周日=6）
        int index = (dayOfWeek + 5) % 7;
        return weekDays[index];
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    // 添加刷新显示的方法
    public void refreshDisplay() {
        if (selectedDate != null) {
            String dateStr = dateKey.format(selectedDate.getTime());
            displayNote(checkinRecords.get(dateStr), dateStr);
        }
    }

    /**
     * 检查指定日期是否是第一次签到（用于决定是否发放勋章）
     * @param dateStr 要检查的日期字符串（格式与 dateKey 相同）
     * @return 如果是第一次签到返回 true，否则返回 false
     */
    private boolean isFirstCheckin(String dateStr) {
        // 检查是否已经有这一天的签到记录
        CheckinRecord record = checkinRecords.get(dateStr);
        return record == null;
    }

    // 签到设置
    private void showCheckinSettings() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_checkin_settings, null);
        CheckBox dailyCheckBox = dialogView.findViewById(R.id.daily_checkbox);
        CheckBox choresCheckBox = dialogView.findViewById(R.id.chores_checkbox);
        CheckBox suggestionsCheckBox = dialogView.findViewById(R.id.suggestions_checkbox);

        // 设置初始状态
        CheckinRecord.DisplaySettings settings = CheckinRecord.getDisplaySettings();
        dailyCheckBox.setChecked(settings.isShowDaily());
        choresCheckBox.setChecked(settings.isShowChores());
        suggestionsCheckBox.setChecked(settings.isShowSuggestions());

        new AlertDialog.Builder(requireContext())
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                // 保存设置
                settings.setShowDaily(dailyCheckBox.isChecked());
                settings.setShowChores(choresCheckBox.isChecked());
                settings.setShowSuggestions(suggestionsCheckBox.isChecked());

                // 更新显示
                refreshDisplay();
            })
            .setNegativeButton("取消", null)
            .show();
    }
}
